package com.ywps.vaas.framework.util

import org.apache.commons.codec.binary.Base64

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, IOException}
import java.util.zip.{GZIPInputStream, GZIPOutputStream}

object GzipUtil {

  /**
   * 使用gzip进行压缩
   *
   * @param str 压缩前的文本
   * @return 返回压缩后的文本
   * @throws IOException 有异常时抛出，由调用者捕获处理
   */
  @throws[IOException]
  def gzip(str: String): String = {
    if (str == null || str.isEmpty) return str
    val out = new ByteArrayOutputStream
    try {
      val gzip = new GZIPOutputStream(out)
      try gzip.write(str.getBytes)
      finally if (gzip != null) gzip.close()
    }
    Base64.encodeBase64String(out.toByteArray)
  }

  /**
   * 使用gzip进行解压缩
   *
   * @param compressedStr 压缩字符串
   * @return 解压字符串
   * @throws IOException 有异常时抛出，由调用者捕获处理
   */
  @throws[IOException]
  def gunzip(compressedStr: String): String = {
    if (compressedStr == null || compressedStr.isEmpty) return compressedStr
    val compressed: Array[Byte] = Base64.decodeBase64(compressedStr)
    val out = new ByteArrayOutputStream
    val in = new ByteArrayInputStream(compressed)
    try {
      val ginzip = new GZIPInputStream(in)
      try {
        val buffer = new Array[Byte](4096)
        var len: Int = -1
        while ( {
          (len = ginzip.read(buffer)) != -1
        }) out.write(buffer, 0, len)
      } finally if (ginzip != null) ginzip.close()
    }
    out.toString
  }

}
